package com.bfxy.rabbit.task.autoconfigure;

import com.bfxy.rabbit.task.parse.ElasticJobConfParser;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;

/**
 * @describte: 自动装配类
 * @program:rabbit-parent
 * @author:zhengdp
 * @create:2021-09-16 14:14:07
 **/
@Configuration
// 配置文件中必须有该前缀，且必须有 namespace 属性和 serverLists 属性，才会加载该配置类
@ConditionalOnProperty(prefix = "elastic.job.zk",
        name = {"namespace","serverLists"},matchIfMissing = false)
@ComponentScan("com.bfxy.rabbit.task.*")
@EnableConfigurationProperties(JobZookeeperProperties.class)
@Slf4j
public class JobParserAutoConfiguration {

    // 将 zookeeper注册中心 注册到Spring容器中
    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter zookeeperRegistryCenter(JobZookeeperProperties jobZookeeperProperties){
        ZookeeperConfiguration zookeeperConfiguration =
                new ZookeeperConfiguration(jobZookeeperProperties.getServerLists(),
                                           jobZookeeperProperties.getNamespace());
        zookeeperConfiguration.setMaxRetries(jobZookeeperProperties.getMaxRetries());
        zookeeperConfiguration.setConnectionTimeoutMilliseconds(jobZookeeperProperties.getConnectionTimeoutMilliseconds());
        zookeeperConfiguration.setSessionTimeoutMilliseconds(jobZookeeperProperties.getSessionTimeoutMilliseconds());
        zookeeperConfiguration.setDigest(jobZookeeperProperties.getDigest());
        zookeeperConfiguration.setBaseSleepTimeMilliseconds(jobZookeeperProperties.getBaseSleepTimeMilliseconds());
        zookeeperConfiguration.setMaxSleepTimeMilliseconds(jobZookeeperProperties.getMaxSleepTimeMilliseconds());

        log.info("初始化job注册中心配置成功，zkaddress : {} , namespace : {}",jobZookeeperProperties.getServerLists(),jobZookeeperProperties.getNamespace());

        return new ZookeeperRegistryCenter(zookeeperConfiguration);
    }

    // 模块装配

    @Bean
    public ElasticJobConfParser elasticJobConfParser(JobZookeeperProperties jobZookeeperProperties,
                                                     ZookeeperRegistryCenter zookeeperRegistryCenter){

        return new ElasticJobConfParser(jobZookeeperProperties,zookeeperRegistryCenter);
    }
}
